package com.ruoyi.system.utils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class ConvertHtmlSvgUtil {

	/***
	 *  1. 把webSvgContainer中需要标记id的进行标记。
	 *  2. 把webSvgContainer中是连接线的内容加上source 和target
	 *  3. 把装填好的内容放到新的容器里面
	 * @param mxgraphXml   DrawGraphInfo 的 graphMxgraphXml属性， 里面是mxgraph的xml内容
	 * @param webSvgContainer  DrawGraphInfo 的 webSvgContainer属性， 里面是html中的页面svg信息
	 * @Param dbSvg   DrawGraphInfo 的  graphXml 属性， 现在应该只有一个svg的壳子，里面有他的偏移量
	 * @Param wholeSvg   前端的整个svg信息
	 * @return
	 */
	public static String convertHtmlSvgToWhole(String mxgraphXml, String webSvgContainer, String dbSvg, String wholeSvg) throws IOException {
		if (StringUtils.isNotEmpty(webSvgContainer)) {
			ByteArrayInputStream dbBis = null;
			ByteArrayInputStream webSvgBis = null;
			ByteArrayInputStream xmlBis = null;
			ByteArrayInputStream wholeSvgBis = null;
			try {
				dbBis = new ByteArrayInputStream(dbSvg.getBytes(StandardCharsets.UTF_8));
				Document dbSvgDocument = Jsoup.parse(dbBis, "UTF-8", "", Parser.xmlParser());
				Document.OutputSettings outputSettings = dbSvgDocument.outputSettings();
				outputSettings.prettyPrint(false);

				Elements gElementList = dbSvgDocument.getElementsByTag("g");
				if (CollectionUtils.isNotEmpty(gElementList)) {
					webSvgBis = new ByteArrayInputStream(webSvgContainer.getBytes(StandardCharsets.UTF_8));
					xmlBis = new ByteArrayInputStream(mxgraphXml.getBytes(StandardCharsets.UTF_8));
					wholeSvgBis = new ByteArrayInputStream(wholeSvg.getBytes(StandardCharsets.UTF_8));
					Element gElement = gElementList.get(0);
					Document mxGraphDocument = Jsoup.parse(xmlBis, "UTF-8", "", Parser.xmlParser());
					Document wholeSvgDocument = Jsoup.parse(wholeSvgBis, "UTF-8", "", Parser.xmlParser());
					Document webSvgDocument = Jsoup.parse(webSvgBis, "UTF-8", "", Parser.xmlParser());
					Elements needCompareElementList = webSvgDocument.getElementsByAttribute("cell-id");
					//获取渐变、纹理等内容 fill="url(#mx-gradient-ffffff-1-ff9933-1-s-0)"
					Elements fillMatchElementList = webSvgDocument.getElementsByAttributeValueContaining("fill", "url(#");
					System.out.println(fillMatchElementList);
					if (CollectionUtils.isNotEmpty(needCompareElementList)) {
						for (Element element : needCompareElementList) {
							String cellId = element.attr("cell-id");
							String mxGraphFindId = cellId;
							if (cellId.startsWith("switch_")) {

							} else if (cellId.startsWith("cell_")) {
								mxGraphFindId = cellId.replace("cell_", "");
							}
							//兄弟节点
							Elements brotherELementList = element.siblingElements();
							if (CollectionUtils.isNotEmpty(brotherELementList)) {
								for (Element brother : brotherELementList) {
									//1. 把webSvgContainer中需要标记id的进行标记。
									String hiddenAttr = brother.attr("visibility");
									if (StringUtils.isNotEmpty(hiddenAttr) && "hidden".equalsIgnoreCase(hiddenAttr)) {
										continue;
									}
									//文本内容
									//<g xmlns="http://www.w3.org/2000/svg">
									//<switch id="switch_18225f9a51c2436b8b2c4ee8d48c7b31_944">
									if (cellId.startsWith("switch_")) {
										Element buildGElement = new Element("g");
										buildGElement.attr("xmlns", "http://www.w3.org/2000/svg");
										Element buildSwitchElement = new Element("switch");
										buildSwitchElement.attr("id", cellId);
										buildGElement.appendChild(buildSwitchElement);
										Elements children = brother.children();
										for (Element child : children) {
											buildSwitchElement.appendChild(child);
										}
										gElement.appendChild(buildGElement);
									} else if (cellId.startsWith("cell_")) {
										brother.attr("xmlns", "http://www.w3.org/2000/svg");
										brother.attr("id", cellId);
										//这个只能有一个
										Element xmlGraphElement = mxGraphDocument.getElementById(mxGraphFindId);
										String source = xmlGraphElement.attr("source");
										String target = xmlGraphElement.attr("target");
										//2. 把webSvgContainer中是连接线的内容加上source 和target

										if (StringUtils.isNotEmpty(source) && StringUtils.isNotEmpty(target)) {
											brother.attr("source", source);
											brother.attr("target", target);
										}
										gElement.appendChild(brother);
									}
								}
							}
						}
					}

					if (CollectionUtils.isNotEmpty(fillMatchElementList)) {
						Set<String> fillIdSet = fillMatchElementList.stream().map(s -> s.attr("fill")).collect(Collectors.toSet());
						for (String idStr : fillIdSet) {
							String id = idStr.substring(idStr.indexOf("url(#") + "url(#".length(), idStr.length() - 1);
							Element fillPatternElement = wholeSvgDocument.getElementById(id);
							if (fillPatternElement != null) {
								gElement.appendChild(fillPatternElement);
							}
						}
					}

				}
				String result = dbSvgDocument.toString();
				result = result.replace("&nbsp;", " ");
				return result;
			} catch (IOException io) {
				log.error(io.getMessage());
			} finally {
				if (dbBis != null) {
					dbBis.close();
				}
				if (webSvgBis != null) {
					webSvgBis.close();
				}
				if (xmlBis != null) {
					xmlBis.close();
				}
			}
		}
		return null;
	}
}

